package com.clock.album;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.resultset.ResultSet;
import ohos.media.photokit.metadata.AVStorage;

import java.util.*;

public class ListFileAbility extends Ability {
    private Map<String,ArrayList<Integer>> dataList=new HashMap<>();
    private ArrayList<String> titleList=new ArrayList<>();
    ListContainer mListView;
    ListFileAdapter listFileAdapter;
    private ArrayList<Integer> intentList=new ArrayList<>();
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_list_file);
        mListView= (ListContainer) findComponentById(ResourceTable.Id_list_view);
        mListView.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                Intent intent1 = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withBundleName("com.clock.album")
                        .withAbilityName("com.clock.album.ShowImageFileAbility")
                        .build();
                intent1.setOperation(operation);
                intent1.setParam("title",titleList.get(i));
                intent1.setIntegerArrayListParam("datalist",dataList.get(titleList.get(i)));
                startAbilityForResult(intent1,10000);
            }
        });
        findComponentById(ResourceTable.Id_back).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onBackPressed();
            }
        });
        showImageFileList();
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        switch (requestCode){
            case 10000:
                if(resultData!=null){
                    intentList=resultData.getIntegerArrayListParam("datalist");
                    onBackPressed();
                }
                break;
        }
    }

    @Override
    protected void onBackPressed() {
        Intent intent=new Intent();
        intent.setIntegerArrayListParam("datalist",intentList);
        setResult(1,intent);
        terminateAbility();
    }

    private void showImageFileList() {
        DataAbilityHelper helper = DataAbilityHelper.creator(this);
        ArrayList<Integer> listAll=new ArrayList<>();
        titleList.add("全部");
        try {
            // columns为null，查询记录所有字段，当前例子表示查询id字段

            DataAbilityPredicates predicates = new DataAbilityPredicates(SELECTION_ALL_FOR_SINGLE_MEDIA_TYPE);
            predicates.setWhereArgs(Arrays.asList(getSelectionArgsForSingleMediaType()));
            ResultSet resultSet = helper.query(AVStorage.Files.fetchResource("external"),PROJECTION, predicates);

//            ResultSet resultSet = helper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, new String[]{AVStorage.Images.Media.ID,"relative_path"}, null);
            resultSet.goToFirstRow();
            while (resultSet != null && resultSet.goToNextRow()) {
                // 获取id字段的值
                int id = resultSet.getInt(resultSet.getColumnIndexForName(AVStorage.Images.Media.ID));
                String relative_path=resultSet.getString(resultSet.getColumnIndexForName("relative_path"));
                if(dataList.containsKey(relative_path)){
                    dataList.get(relative_path).add(id);
                }else {
                    titleList.add(relative_path);
                    ArrayList<Integer> list=new ArrayList<>();
                    list.add(id);
                    dataList.put(relative_path,list);
                }
                listAll.add(id);
            }
            dataList.put("全部",listAll);
            listFileAdapter=new ListFileAdapter(this,titleList,dataList);
            mListView.setItemProvider(listFileAdapter);
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
    }

    private static final String[] PROJECTION = {
            AVStorage.AVBaseColumns.ID,
            AVStorage.AVBaseColumns.MIME_TYPE,
            AVStorage.AVBaseColumns.SIZE,
            "relative_path"
    };
    // === params for album ALL && showSingleMediaType: true ===
    private static final String SELECTION_ALL_FOR_SINGLE_MEDIA_TYPE =
            AVStorage.AVBaseColumns.MIME_TYPE + "=?"
                    + " OR " + AVStorage.AVBaseColumns.MIME_TYPE + "=?"
                    + " OR " + AVStorage.AVBaseColumns.MIME_TYPE + "=?"
                    + " OR " + AVStorage.AVBaseColumns.MIME_TYPE + "=?"
                    + " OR " + AVStorage.AVBaseColumns.MIME_TYPE + "=?"
                    + " OR " + AVStorage.AVBaseColumns.MIME_TYPE + "=?"
                    + " OR " + AVStorage.AVBaseColumns.MIME_TYPE + "=?"
                    + " AND " + AVStorage.AVBaseColumns.SIZE + ">0";

    private static String[] getSelectionArgsForSingleMediaType() {
        return new String[]{"image/jpeg",
                "image/png",
                "image/gif",
                "image/bmp",
                "image/heif",
                "image/heic",
                "image/webp"
        };
    }
}
